import { useEffect, useState } from "react";
import "../../css/sign_up.less";
import instance from "../utils/https.js";
import newTime from "./data/time";
import dayjs from "dayjs";
import Form from "./components/Form.tsx";
import { useNavigate } from "react-router-dom";

// 定义表单数据的类型
interface FormData {
  _id: string;
  name: string; // 姓名
  position: string; // 职位
  introduce: string; // 简历（已更名为introduce）
  profileImage: string; // 头像URL
}

export default function Sign_up() {
  const user_id = localStorage.getItem("_id");
  const [time, setTime] = useState<string>(""); // 活动结束时间
  const [isFalse, setIsFalse] = useState<boolean>(true); // 活动是否结束
  const [showPopup, setShowPopup] = useState<boolean>(false); // 控制弹窗显示
  const nav = useNavigate();

  // 获取活动时间并判断活动是否结束
  const getTime = async () => {
    try {
      const { activityMsgs } = (await instance.get("/getactives")) as {
        activityMsgs: any;
      };
      const formattedTime = dayjs(activityMsgs[0].endTime).format(
        "YYYY-MM-DD HH:mm:ss"
      );
      setTime(formattedTime);

      const isExpired = new Date(formattedTime) > new Date(newTime);
      setIsFalse(isExpired);
    } catch (err) {
      console.error("获取活动时间错误", err);
    }
  };

  // 组件加载时获取活动时间
  useEffect(() => {
    getTime();
  }, []);

  // 处理表单提交
  const handleSubmit = async (data: FormData) => {
    if (user_id === null) {
      throw new Error("user_id 不能为 null");
    }

    data._id = user_id;

    console.log(data, "提交数据");

    const result: any = await instance.put("/apply/addApply", data);

    console.log(result, "返回的数据");

    if (result.code === 200) {
      setShowPopup(true);
      setTimeout(() => {
        nav("/app/layout/home");
        setTimeout(() => {
          setShowPopup(false);
        }, 2000); // 隐藏弹窗的延迟
      },3000);
    } else {
      console.error("报名失败", result.msg);
    }
  };

  return (
    <div className="Sign_home">
      {/* 弹窗 */}
      {showPopup && (
        <div className="popups">
          <div className="popups-content">
            <h3>🎉 已报名，等待审核通过</h3>
          </div>
        </div>
      )}

      {isFalse ? (
        <div>
          <Form onSubmit={handleSubmit} time={time}></Form>
        </div>
      ) : (
        <div className="NoTime-Div">
          <button disabled style={{ color: "white" }}>
            报名已结束
          </button>
          <p style={{ color: "white" }}>
            报名结束时间：{time} 现在时间 {newTime}
          </p>
        </div>
      )}
    </div>
  );
}
